import 'dart:async';

import 'package:dio/dio.dart'
    as dio_package; // 用于发请求 避免get和dio库里面都有FormData导致冲突
import 'package:eleapp/res/strings.dart';
import 'package:eleapp/util/formatter/customized_length_formatter.dart';
import 'package:eleapp/util/formatter/customized_maxvalue_formatter.dart';
import 'package:eleapp/util/formatter/customized_text_formatter.dart';
import 'dart:io'; // 使用File方法 解析文件本地文件，展示图片
import '../../dio/http_request.dart';
import '../../dio/api.dart';
import '../../util/toast_util.dart';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

// List imglist = [
//   'https://img1.baidu.com/it/u=32218479,595384475&fm=253&fmt=auto&app=138&f=JPEG?w=480&h=720',
//   'https://i0.hdslb.com/bfs/archive/797c7943503865a7dc9e65a07a4cbaae596dd2d5.jpg',
// ];

class PhotoPage extends StatefulWidget {
  // 此处用原生定义的 arguments接受参数，因为跳转页面用的原生跳转
  final Map arguments;
  const PhotoPage({super.key, required this.arguments});

  @override
  State<PhotoPage> createState() => _PhotoPageState();
}

class _PhotoPageState extends State<PhotoPage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print('widget.arguments');
    print(widget.arguments);
  }

  var technical = TextEditingController();
  var quality = TextEditingController();

  // 图片数组
  List imglist = [];

  // 使用ImagePicker前必须先实例化
  final ImagePicker _imagePicker = ImagePicker();

  // ImagePicker获取内容后返回的对象是XFile
  // XFile? image;
  List<XFile>? imageList;

  // 选取多张图片
  selectMultiImage() async {
    List<XFile>? images = await _imagePicker.pickMultiImage(
      // maxHeight: 250, // 用来指定选择图片的最大宽度，若图片超过该宽度，将等比例缩小图片再返回，默认返回原始图片
      // maxWidth: 250, // 用来指定选择图片的最大高度，若图片超过该高度，将等比例缩小图片再返回，默认返回原始图片
      // imageQuality: 0, // 用来修改图片返回的质量（压缩），取值在0-100，越大返回图片的质量越高，默认为100，即原始图片
      limit: 9 - imglist.length,
    );
    if (images.isNotEmpty) {
      setState(() {
        images.forEach((value) => imglist.add(value.path));
      });
    }
  }

  // 打开相机拍摄选择相片
  selectCamera() async {
    XFile? photo = await _imagePicker.pickImage(
      // source: ImageSource.gallery, // 选择相册 且只为单张
      source: ImageSource.camera, // 拍摄
      preferredCameraDevice: CameraDevice.rear,
    );

    if (photo != null) {
      setState(() {
        imglist.add(photo.path);
      });
    }
  }

  // 图片数组加载
  List<Widget> loadImgData(List data) {
    List<Widget> formatList = [];

    for (int i = 0; i < data.length; i++) {
      formatList.add(Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          border: Border.all(width: 1, color: Colors.black12),
          // color: Colors.red,
        ),
        child: Stack(
          children: [
            GestureDetector(
              onTap: () {
                Get.toNamed('/photopreview',
                    arguments: {'imageList': imglist, 'curIndex': i});
              },
              child: Hero(
                tag: "img$i",
                child: Align(
                  alignment: const Alignment(0, 0),
                  child: Container(
                    width: double.infinity,
                    height: double.infinity,
                    alignment: const Alignment(0, 0),
                    decoration: BoxDecoration(
                      border: Border.all(width: 1, color: Colors.black12),
                      // color: Colors.red,
                    ),
                    // child: Image.network(
                    //   data[i],
                    //   fit: BoxFit.cover,
                    //   width: double.infinity,
                    //   height: double.infinity,
                    // ),
                    child: Image.file(
                      File(data[i]), // 必须利用File方法传入图片的路径这样的形式
                      fit: BoxFit.cover,
                      width: double.infinity,
                      height: double.infinity,
                    ),
                  ),
                ),
              ),
            ),
            Positioned(
                top: 0,
                right: 0,
                child: SizedBox(
                  width: 30,
                  height: 30,
                  child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                          padding: EdgeInsets.zero,
                          backgroundColor: Colors.white70),
                      iconAlignment: IconAlignment.end,
                      onPressed: () {
                        setState(() {
                          imglist.removeRange(i, i + 1);
                        });
                      },
                      child: const Icon(
                        Icons.delete,
                        size: 20,
                        color: Color.fromARGB(166, 244, 76, 54),
                      )),
                )),
          ],
        ),
      ));
    }

    if (data.length < 9) {
      formatList.add(Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          border: Border.all(width: 1, color: Colors.black12),
          // color: Colors.red,
        ),
        child: Stack(
          children: [
            Align(
              // top: 0,
              // left: 0,
              alignment: const Alignment(0, 0),
              child: SizedBox(
                width: double.infinity,
                height: double.infinity,
                child: ElevatedButton(
                    onPressed: () async {
                      FocusScope.of(context).requestFocus(FocusNode());
                      var res = await _showbottomDialog();
                      print('加图');
                      print(res);
                    },
                    style: ButtonStyle(
                      shape: WidgetStateProperty.all(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(0),
                        ),
                      ), // 去除圆角
                    ),
                    child: const Icon(
                      Icons.add,
                      size: 50,
                    )),
              ),
            ),
          ],
        ),
      ));
    }
    return formatList;
  }

  // 底部弹出框
  _showbottomDialog() async {
    var result = await showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
            height: 200,
            child: Stack(
              children: [
                Align(
                  alignment: const Alignment(0, -0.8),
                  child: SizedBox(
                    width: 300,
                    child: ElevatedButton(
                      style: ButtonStyle(
                        backgroundColor: WidgetStateProperty.all(Colors.blue),
                        foregroundColor: WidgetStateProperty.all(Colors.white),
                      ),
                      onPressed: () async {
                        selectMultiImage();
                        Navigator.pop(context, '选择照片(长按多选)');
                      },
                      child: Text(StringStyles.multiplePhoto.tr),
                    ),
                  ),
                ),
                Align(
                  alignment: const Alignment(0, -0.15),
                  child: SizedBox(
                    width: 300,
                    child: ElevatedButton(
                      style: ButtonStyle(
                        backgroundColor: WidgetStateProperty.all(Colors.blue),
                        foregroundColor: WidgetStateProperty.all(Colors.white),
                      ),
                      onPressed: () async {
                        selectCamera();
                        Navigator.pop(context, '拍摄');
                      },
                      child: Text(StringStyles.camera.tr),
                    ),
                  ),
                ),
                Align(
                  alignment: const Alignment(0, 0.7),
                  child: SizedBox(
                    width: 300,
                    child: ElevatedButton(
                      onPressed: () async {
                        Navigator.pop(context, '取消');
                      },
                      child: Text(StringStyles.cancel.tr),
                    ),
                  ),
                ),
              ],
            ),
          );
        });
    return result;
  }

  // 提交发送确认提示
  _alertDialog() async {
    var result = await showDialog(
        barrierDismissible: false, //表示点击灰色背景的时候是否消失弹出框
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("${StringStyles.hintMessage.tr}!"),
            content: Text(StringStyles.submitPicAndScoreTip.tr),
            actions: <Widget>[
              TextButton(
                child: Text(StringStyles.cancel.tr),
                onPressed: () {
                  Navigator.pop(context, 'Cancle');
                },
              ),
              TextButton(
                child: Text(StringStyles.confirm.tr),
                onPressed: () async {
                  List resultList = [];
                  for (int i = 0; i < imglist.length; i++) {
                    await _repeatedlyRequest(imglist[i], resultList);
                  }
                  print(resultList);
                  print(resultList.join(','));

                  Map params = {
                    'lesson_id': widget.arguments['lesson_id'],
                    'group_id': widget.arguments['group_id'],
                    'score1': technical.text,
                    'score2': quality.text,
                    'imgs': resultList.join(',')
                  };
                  // 评分
                  int score =
                      await Request2.post<int>(Api.groupevaluate, params);

                  if (score == 0) {
                    technical.text = '';
                    quality.text = '';
                    print('评分成功');

                    setState(() {
                      imglist.clear();
                    });
                    ToastUtils.show(StringStyles.submited.tr);

                    Timer(const Duration(milliseconds: 1200), () {
                      // 必须使用接受到的context 本页面的context返回时会被销毁
                      // 此处返回后，上一页面会进行数据更新
                      print('返回上一页面');
                      Navigator.of(widget.arguments['context']).pop();
                      Get.back();
                    });
                  }
                },
              )
            ],
          );
        });
    print(result);
  }

  // 重复调用发送图片 并收集结果到传递的数组
  _repeatedlyRequest(String url, List resList) async {
    Future<dio_package.FormData> createFormData() async {
      String fileName = url.split('/').last;

      return dio_package.FormData.fromMap({
        'date': DateTime.now().toIso8601String(),
        'imgFile': await dio_package.MultipartFile.fromFile(
          url,
          filename: fileName,
        ),
      });
    }

    Map res = await Request2.post<Map>(Api.uploadFile, await createFormData());
    // print(res);
    // print('图片结果');
    // resList.add(res['url']);
    resList.add(res['img']);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        // 收回键盘
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Scaffold(
          // 避免输入框弹出 影响布局（底部溢出、元素被迫滑动上移）
          resizeToAvoidBottomInset: false,
          appBar: AppBar(
            title: Text(StringStyles.cameraScore.tr),
            backgroundColor: Colors.blue,
          ),
          body: SizedBox(
            height: double.infinity,
            child: Column(
              children: [
                Container(
                  margin: const EdgeInsets.only(top: 40, bottom: 10),
                  alignment: const Alignment(0, 0),
                  height: 60,
                  // color: Colors.red,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Container(
                        padding: const EdgeInsets.only(left: 30),
                        // width: 60,
                        child: Text(
                          '${StringStyles.skillScore.tr}：',
                          textAlign: TextAlign.start,
                          style: const TextStyle(
                            fontSize: 14,
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 70,
                        height: 30,
                        child: TextField(
                          controller: technical,
                          decoration: const InputDecoration(
                            contentPadding:
                                EdgeInsets.only(left: 20.0, top: 1, bottom: 14),
                          ),
                          keyboardType: TextInputType.number,
                          inputFormatters: [
                            // 限制最大值
                            MaxValueTextFormatter(maxValue: 100),

                            ///输入长度和格式限制
                            CustomizedLengthTextInputFormatter(3),
                            CustomizedTextInputFormatter(
                              // 限制只能数字 且不以0开头
                              filterPattern: RegExp("^(?!0)[0-9]*"),
                            ),
                          ],
                          style: const TextStyle(fontSize: 24, height: 1),
                          onChanged: (value) {
                            print(value);
                          },
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.only(left: 10),
                        // width: 130,
                        child: Text(
                          '${StringStyles.civilizeScore.tr}：',
                          textAlign: TextAlign.start,
                          style: const TextStyle(
                            fontSize: 14,
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 70,
                        height: 30,
                        child: TextField(
                          controller: quality,
                          decoration: const InputDecoration(
                            contentPadding:
                                EdgeInsets.only(left: 20.0, top: 1, bottom: 14),
                          ),
                          keyboardType: TextInputType.number,
                          inputFormatters: [
                            // 限制最大值
                            MaxValueTextFormatter(maxValue: 100),

                            ///输入长度和格式限制
                            CustomizedLengthTextInputFormatter(3),
                            CustomizedTextInputFormatter(
                              // 限制只能数字 且不以0开头
                              filterPattern: RegExp("^(?!0)[0-9]*"),
                            ),
                          ],
                          style: const TextStyle(fontSize: 24, height: 1),
                          onChanged: (value) {
                            print(value);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  flex: 4,
                  child: Container(
                    // margin: const EdgeInsets.only(top: 100),
                    // height: double.infinity,
                    // height: 500,
                    // color: Colors.yellow,
                    child: ListView(
                      padding: const EdgeInsets.only(top: 30),
                      children: [
                        Padding(
                          padding: const EdgeInsets.only(left: 30, bottom: 10),
                          child: Text(
                            '${StringStyles.attachedMap.tr}：',
                            style: const TextStyle(fontSize: 14),
                          ),
                        ),
                        SizedBox(
                          // width: 100,
                          height: 1500,
                          // color: Colors.deepOrangeAccent,
                          child: GridView.count(
                            padding: const EdgeInsets.only(left: 20, right: 20),
                            crossAxisCount: 3, // 每行最多几个
                            childAspectRatio: 1, // 宽高比
                            mainAxisSpacing: 1, // 行边距
                            crossAxisSpacing: 1, // 列边距
                            children: loadImgData(imglist),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                Expanded(
                    flex: 1,
                    child: Container(
                      // height: 60,
                      // margin: const EdgeInsets.only(top: 60),
                      alignment: const Alignment(0, 0),
                      // color: Colors.amber,
                      child: SizedBox(
                        width: 240,
                        child: ElevatedButton(
                          style: ButtonStyle(
                            backgroundColor:
                                WidgetStateProperty.all(Colors.blue),
                            foregroundColor:
                                WidgetStateProperty.all(Colors.white),
                          ),
                          onPressed: () async {
                            FocusScope.of(context).requestFocus(FocusNode());

                            if (technical.text == '' || quality.text == '') {
                              return ToastUtils.show(
                                  StringStyles.finishScore.tr);
                            }
                            if (imglist.isEmpty) {
                              return ToastUtils.show(
                                  StringStyles.finishSelectPhoto.tr);
                            }
                            print(await _alertDialog());
                          },
                          child: Text(StringStyles.submitSend.tr),
                        ),
                      ),
                    ))
              ],
            ),
          )),
    );
  }
}
